package my.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtil {
	public static final String UTF8 = "UTF-8";
	public static final String GBK = "GBK";
	public static final String GB2312 = "GB2312";
	public static final String ISO8859_1 = "ISO8859-1";

	private static final Log log = LogFactory.getLog(HttpUtil.class);

	public Object post(String url, Map<String, String> params, String charset) {
		log.info("post "+url+" starting...");
		HttpClient httpclient = null;
		HttpPost post = null;
		String responseText = "";
		try {
			httpclient = new DefaultHttpClient();
			post = new HttpPost(url);
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(getParams(params));
			post.setEntity(entity);
			log.info("httpclient executing...");
			HttpResponse response = httpclient.execute(post);
			log.info("httpclient executed.");
			int status = response.getStatusLine().getStatusCode();
			log.info(">>>HttpStatus:" + status);
			if (status == HttpStatus.SC_OK) {
				responseText = EntityUtils.toString(response.getEntity(), UTF8);
			} else {
				System.out.println("执行检测业务信息失败,网络错误或配置文件出错.");
			}
			log.info("==========================post "+url+" over==================================");
		} catch (Exception e) {
			log.error("request "+url+" exception!!!", e);
		} finally {
			if (post != null)
				post.abort();
			if (httpclient != null)
				httpclient.getConnectionManager().shutdown();
		}
		return responseText;
	}
	/**
	 * 参数转换,将map转为list中存放NameValuePair
	 * @param map
	 * @return 转换完毕的
	 */
	private List<NameValuePair> getParams(Map<String,String> map){
		List<NameValuePair> param = new ArrayList<NameValuePair>();
		for(String key:map.keySet())	{
			param.add(new BasicNameValuePair("dateparam", map.get(key)));
		}
		return param;
	}
}
